'use client';

import { useState, useEffect } from 'react';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { categories, products } from '@/lib/mockData';

interface UnboxPageProps {
  params: {
    id: string;
  };
}

export default function UnboxPage({ params }: UnboxPageProps) {
  const { state, dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [mounted, setMounted] = useState(false);
  const [isUnboxing, setIsUnboxing] = useState(false);
  const [unboxResult, setUnboxResult] = useState<any>(null);
  const [showResult, setShowResult] = useState(false);
  const [animationStep, setAnimationStep] = useState(0); // 0: 准备, 1: 开箱中, 2: 结果

  const boxId = params.id;
  const box = state.purchasedBoxes.find(b => b.id === boxId);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-xl">加载中...</div>
      </div>
    );
  }

  if (!box) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">❌</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-4">盲盒不存在</h2>
          <p className="text-gray-600 mb-6">该盲盒可能已被删除或不存在</p>
          <a href="/profile" className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
            返回个人中心
          </a>
        </div>
      </div>
    );
  }

  if (box.isUnboxed) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">🎁</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-4">该盲盒已开启</h2>
          <p className="text-gray-600 mb-6">您已经开启过这个盲盒了</p>
          <a href="/profile" className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
            返回个人中心
          </a>
        </div>
      </div>
    );
  }

  const category = categories.find(c => c.id === box.productCategory);
  const product = products.find(p => p.id === box.productId);

  // 开箱逻辑
  const handleUnbox = async () => {
    if (isUnboxing) return;
    
    setIsUnboxing(true);
    setAnimationStep(1);
    
    // 第一阶段：开箱动画 (3秒)
    setTimeout(() => {
      // 生成开箱结果
      const generateUnboxResult = (category: string) => {
        const rarities = ['common', 'rare', 'epic', 'legendary'];
        const weights = [50, 30, 15, 5]; // 权重：普通50%，稀有30%，史诗15%，传说5%
        
        let randomNum = Math.random() * 100;
        let selectedRarity = 'common';
        let cumulativeWeight = 0;
        
        for (let i = 0; i < weights.length; i++) {
          cumulativeWeight += weights[i];
          if (randomNum <= cumulativeWeight) {
            selectedRarity = rarities[i];
            break;
          }
        }
        
        let items: any[] = [];
        let actualValue = 0;
        let description = '';
        
        switch (category) {
          case 'virtual':
            items = [
              { name: '爱奇艺会员月卡', value: 19, desc: '30天影视无限看' },
              { name: '网易云音乐VIP', value: 15, desc: '高品质音乐体验' },
              { name: '美团30元券', value: 30, desc: '外卖红包券' },
              { name: 'Steam钱包20元', value: 20, desc: '游戏购买代金券' },
              { name: '腾讯视频VIP月卡', value: 18, desc: '追剧必备' },
              { name: '滴滴出行券50元', value: 50, desc: '出行优惠券' }
            ];
            break;
          case 'digital':
            items = [
              { name: '蓝牙耳机', value: 89, desc: 'TWS无线耳机' },
              { name: '充电宝10000mAh', value: 59, desc: '快充移动电源' },
              { name: 'Type-C数据线', value: 25, desc: '高速充电线' },
              { name: '无线鼠标', value: 79, desc: '2.4G无线光学鼠标' },
              { name: '机械键盘', value: 299, desc: '青轴机械键盘' },
              { name: '蓝牙音箱', value: 128, desc: '便携立体声音箱' }
            ];
            break;
          case 'food':
            items = [
              { name: '星巴克中杯券', value: 35, desc: '任意中杯饮品' },
              { name: '麦当劳套餐券', value: 42, desc: '巨无霸套餐' },
              { name: '海底捞200元券', value: 200, desc: '火锅代金券' },
              { name: '喜茶任意杯券', value: 28, desc: '新茶饮品券' },
              { name: '肯德基全家桶券', value: 89, desc: '家庭聚餐首选' },
              { name: '必胜客比萨券', value: 108, desc: '大份比萨券' }
            ];
            break;
          case 'anime':
            items = [
              { name: '鸣人手办', value: 128, desc: '火影忍者周边' },
              { name: '二次元徽章套装', value: 45, desc: '6枚精美徽章' },
              { name: 'Cosplay发箍', value: 35, desc: '猫耳朵发箍' },
              { name: '限定海报', value: 88, desc: '签名版海报' },
              { name: '路飞手办', value: 158, desc: '海贼王周边' },
              { name: '初音未来抱枕', value: 98, desc: '等身抱枕' }
            ];
            break;
          default:
            items = [{ name: '神秘小礼品', value: 20, desc: '意外惊喜' }];
        }
        
        const randomItem = items[Math.floor(Math.random() * items.length)];
        const rarityMultiplier = selectedRarity === 'legendary' ? 2.5 : 
                                selectedRarity === 'epic' ? 2 : 
                                selectedRarity === 'rare' ? 1.5 : 1;
        
        actualValue = Math.round(randomItem.value * rarityMultiplier);
        description = randomItem.desc;
        
        return {
          id: `UNBOX_${Date.now()}`,
          purchasedBoxId: boxId,
          actualItem: randomItem.name,
          actualValue: actualValue,
          category: category,
          rarity: selectedRarity,
          description: description,
          image: '/api/placeholder/200/200',
          satisfaction: Math.floor(Math.random() * 2) + 4, // 4-5星
          unboxDate: new Date().toISOString()
        };
      };
      
      const result = generateUnboxResult(box.productCategory);
      setUnboxResult(result);
      setAnimationStep(2);
      
      // 第二阶段：显示结果
      setTimeout(() => {
        setShowResult(true);
        
        // 更新状态
        dispatch({
          type: 'UNBOX_ITEM',
          payload: {
            boxId: boxId,
            unboxResult: result
          }
        });
        
        setIsUnboxing(false);
        showToast(`🎉 开箱成功！获得了 ${result.actualItem}！`, 'success');
      }, 1000);
      
    }, 3000);
  };

  const getRarityColor = (rarity: string) => {
    switch (rarity) {
      case 'legendary': return 'from-yellow-400 via-yellow-500 to-yellow-600';
      case 'epic': return 'from-purple-400 via-purple-500 to-purple-600';
      case 'rare': return 'from-blue-400 via-blue-500 to-blue-600';
      default: return 'from-gray-400 via-gray-500 to-gray-600';
    }
  };

  const getRarityText = (rarity: string) => {
    switch (rarity) {
      case 'legendary': return '传说';
      case 'epic': return '史诗';
      case 'rare': return '稀有';
      default: return '普通';
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-blue-900 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* 返回按钮 */}
        <div className="mb-8">
          <a href="/profile" className="inline-flex items-center text-white hover:text-yellow-300 transition-colors">
            <span className="mr-2">←</span>
            返回个人中心
          </a>
        </div>

        {/* 开箱区域 */}
        <div className="text-center">
          {/* 盲盒信息 */}
          <div className="mb-8">
            <h1 className="text-4xl font-bold text-white mb-4">{box.productName}</h1>
            <p className="text-xl text-gray-300">购买价格: ¥{box.price}</p>
          </div>

          {/* 开箱动画区域 */}
          <div className="relative mx-auto mb-8" style={{ width: '400px', height: '400px' }}>
            {/* 背景光效 */}
            <div className={`absolute inset-0 rounded-full ${
              animationStep === 1 ? 'animate-pulse bg-gradient-to-r from-yellow-400/20 to-orange-400/20' : ''
            }`}></div>
            
            {/* 盲盒 */}
            <div className={`relative w-full h-full transition-all duration-1000 ${
              animationStep === 1 ? 'animate-bounce' : ''
            } ${animationStep === 2 ? 'scale-110' : ''}`}>
              
              {animationStep < 2 ? (
                // 未开箱状态
                <div className={`w-full h-full bg-gradient-to-br ${product?.bgColor || 'from-gray-400 to-gray-600'} rounded-2xl flex items-center justify-center shadow-2xl`}>
                  <div className="text-center">
                    <div className="text-8xl mb-4">{category?.icon || '📦'}</div>
                    {animationStep === 1 && (
                      <div className="text-white text-xl font-bold animate-pulse">
                        🎁 开箱中...
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                // 开箱结果
                <div className={`w-full h-full bg-gradient-to-br ${getRarityColor(unboxResult?.rarity)} rounded-2xl flex items-center justify-center shadow-2xl border-4 border-white/50`}>
                  <div className="text-center text-white">
                    <div className="text-6xl mb-4">🎁</div>
                    <div className="text-2xl font-bold mb-2">{unboxResult?.actualItem}</div>
                    <div className="text-lg opacity-90">{getRarityText(unboxResult?.rarity)}</div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 开箱按钮或结果详情 */}
          {!showResult ? (
            <div>
              <button
                onClick={handleUnbox}
                disabled={isUnboxing}
                className={`px-12 py-4 rounded-xl font-bold text-2xl transition-all ${
                  isUnboxing
                    ? 'bg-gray-600 text-white cursor-not-allowed'
                    : 'bg-gradient-to-r from-yellow-400 to-orange-400 text-black hover:shadow-2xl hover:scale-105'
                }`}
              >
                {isUnboxing ? '🎰 开箱中...' : '🎯 开启盲盒'}
              </button>
              
              <div className="mt-6 text-gray-300">
                <p>点击按钮开启您的神秘盲盒</p>
                <p className="text-sm mt-2">每个盲盒都有惊喜等着您！</p>
              </div>
            </div>
          ) : (
            // 开箱结果详情
            <div className="bg-white/10 backdrop-blur-sm rounded-xl p-8 text-white">
              <div className="mb-6">
                <h2 className="text-3xl font-bold mb-4">🎉 恭喜您获得</h2>
                <div className={`inline-block px-4 py-2 rounded-full bg-gradient-to-r ${getRarityColor(unboxResult?.rarity)} text-white font-bold text-lg`}>
                  {getRarityText(unboxResult?.rarity)} 物品
                </div>
              </div>
              
              <div className="grid md:grid-cols-2 gap-6 text-left">
                <div>
                  <h3 className="text-lg font-semibold mb-2">物品信息</h3>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-gray-300">物品名称:</span>
                      <span className="font-medium">{unboxResult?.actualItem}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-300">实际价值:</span>
                      <span className="font-medium text-green-400">¥{unboxResult?.actualValue}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-300">稀有度:</span>
                      <span className="font-medium">{getRarityText(unboxResult?.rarity)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-300">满意度:</span>
                      <span className="font-medium">{'⭐'.repeat(unboxResult?.satisfaction || 0)}</span>
                    </div>
                  </div>
                </div>
                
                <div>
                  <h3 className="text-lg font-semibold mb-2">收益分析</h3>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-gray-300">购买价格:</span>
                      <span className="font-medium">¥{box.price}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-300">获得价值:</span>
                      <span className="font-medium">¥{unboxResult?.actualValue}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-300">价值比:</span>
                      <span className={`font-medium ${
                        (unboxResult?.actualValue || 0) > box.price ? 'text-green-400' : 'text-red-400'
                      }`}>
                        {(((unboxResult?.actualValue || 0) / box.price) * 100).toFixed(0)}%
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="mt-8 space-y-4">
                <div className="text-center">
                  <p className="text-gray-300">{unboxResult?.description}</p>
                </div>
                
                <div className="flex flex-col sm:flex-row gap-4 justify-center">
                  <a href="/profile" className="bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
                    📱 查看收藏
                  </a>
                  <a href="/" className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
                    🛍️ 继续购买
                  </a>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}